<script setup name="">
import { getToken } from '@/utils/auth'
import {
  listExcel,
  delExcelInfo,
  delExcelInfos,
  updateCredits,
  addCredits
} from '@/api/commission/excel'
import { parseTimes } from '@/utils/ruoyi'
import { ElMessage } from 'element-plus'
import { shortcuts, defaultTime1 } from '@/utils/dateSet'
const { proxy } = getCurrentInstance()
const userList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const dateRange = ref([])
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url:
    import.meta.env.VITE_APP_BASE_API +
    '/credits/statementOfAccount/importStatementOfAccount'
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    channel: undefined, // 渠道
    orderId: undefined, // 达成订单id
    startTime: undefined, // 开始时间
    endTime: undefined // 结束时间
  },
  rules: {
    userName: [
      { required: true, message: '用户名称不能为空', trigger: 'blur' },
      {
        min: 2,
        max: 20,
        message: '用户名称长度必须介于 2 和 20 之间',
        trigger: 'blur'
      }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)
const changeDate = () => {
  queryParams.value.startTime = new Date(dateRange.value[0]).getTime()
  queryParams.value.endTime = new Date(dateRange.value[1]).getTime()
}
/** 查询用户列表 */
function getList () {
  loading.value = true
  listExcel(proxy.addDateRange(queryParams.value)).then(res => {
    loading.value = false
    userList.value = res.rows
    total.value = res.total
  })
}

/** 搜索按钮操作 */
function handleQuery () {
  queryParams.value.pageNum = 1
  getList()
}
/** 重置按钮操作 */
function resetQuery () {
  dateRange.value = []
  proxy.resetForm('queryRef')
  queryParams.value.channel = undefined
  queryParams.value.orderId = undefined
  queryParams.value.startTime = undefined
  queryParams.value.endTime = undefined
  // proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery()
}
/** 删除按钮操作 */
function handleDelete (row) {
  proxy.$modal
    .confirm('是否确认删除编号为"' + row.id + '"的数据项？')
    .then(function () {
      return delExcelInfo(row.id)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
/** 导出按钮操作 */
// function handleExport () {
//   proxy.download(
//     'system/info/export',
//     {
//       ...queryParams.value
//     },
//     `话费领取信息记录对比-${new Date().getTime()}.xlsx`
//   )
// }
// 批量删除  选择条数
function handleSelectionChange (selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
  console.log(ids.value, '遍历id')
}
function handleDeletes () {
  delExcelInfos({ ids: ids.value }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  })
}
/** 导入按钮操作 */
function handleImport () {
  upload.title = '用户导入'
  upload.open = true
}
/** 下载模板操作 */
// function importTemplate () {
//   proxy.download(
//     '/credits/statementOfAccount/importStatementOfAccount',
//     {},
//     `话费领取信息-${new Date().getTime()}.xlsx`
//   )
// }
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs['uploadRef'].handleRemove(file)
  // if (response.data.have.length || response.data.error.length) {
  //   proxy.$alert(
  //     `<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>
  //       已更新：<div class='el-textarea'><textarea cols='40' rows='5' class="el-textarea__inner">${response.data.have} </textarea></div>
  //       导入失败：<div class='el-textarea'><textarea cols='40' rows='5' class="el-textarea__inner">${response.data.error} </textarea></div>
  //       </div>`,
  //     '导入结果',
  //     { dangerouslyUseHTMLString: true }
  //   )
  // } else {
  //   proxy.$alert(
  //     "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
  //       response.msg +
  //       '</div>',
  //     '导入结果',
  //     { dangerouslyUseHTMLString: true }
  //   )
  // }
  if (response.code == 500) {
    ElMessage({
      message: '导入失败，' + response.msg,
      type: 'error',
      showClose: true,
      duration: 0
    })
  } else if (response.code == 200) {
    ElMessage({
      message: '导入成功',
      type: 'success'
    })
  }
  getList()
}
/** 提交上传文件 */
function submitFileForm () {
  proxy.$refs['uploadRef'].submit()
}
/** 重置操作表单 */
function reset () {
  form.value = {}
  proxy.resetForm('commission')
}
/** 取消按钮 */
function cancel () {
  open.value = false
  reset()
}
/** 新增按钮操作 */
function handleAdd () {
  reset()
  open.value = true
  title.value = '添加'
}
/** 修改按钮操作 */
function handleUpdate (row) {
  reset()
  form.value = JSON.parse(JSON.stringify(row)) // 赋值需要深拷贝
  console.log(new Date(+form.value.accountDate).getTime(), 666)
  console.log(form.value.accountDate, 888)
  form.value.accountDate = new Date(+form.value.accountDate).getTime()
  open.value = true
  title.value = '修改'
}
/** 提交按钮 */
function submitForm () {
  proxy.$refs['commission'].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        updateCredits({
          ...form.value,
          accountDate: new Date(form.value.accountDate).getTime(),
          activeTime: new Date(form.value.activeTime).getTime()
        }).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        ;(form.value.accountDate = new Date(form.value.accountDate).getTime()),
          (form.value.activeTime = new Date(form.value.activeTime).getTime())
        addCredits(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

getList()
</script>

<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item
        label="渠道"
        prop="channel
"
      >
        <el-input
          v-model="queryParams.channel"
          placeholder="请输入渠道"
          clearable
        />
      </el-form-item>
      <el-form-item label="达成订单id" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入达成订单id"
          clearable
        />
      </el-form-item>
      <el-form-item label="账单时间" prop="date">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="defaultTime1"
          type="datetimerange"
          :shortcuts="shortcuts"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="changeDate"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDeletes"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="ID"
        align="center"
        key="id"
        prop="id"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="账单时间"
        align="center"
        prop="accountDate"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ parseTimes(scope.row.accountDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="渠道"
        align="center"
        prop="channel"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="上游id"
        align="center"
        prop="upStreamId"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="套餐id"
        align="center"
        prop="skuId"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="套餐名称"
        align="center"
        prop="skuName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="激活时间"
        align="center"
        prop="activeTime"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ parseTimes(scope.row.activeTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="公司收单政策"
        align="center"
        prop="companyPolicy"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="店铺分佣政策"
        align="center"
        prop="shopPolicy"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="公司奖罚类别"
        align="center"
        prop="companyRewardType"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="店铺奖罚类别"
        align="center"
        prop="shopRewardType"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="仓库"
        align="center"
        prop="warehouse"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="台账名称"
        align="center"
        prop="meetingName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="达成订单id"
        align="center"
        prop="orderId"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="是否结算"
        align="center"
        prop="settlement"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="佣金"
        align="center"
        prop="commissions"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="店铺分佣"
        align="center"
        prop="deptCommissions"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="充值"
        align="center"
        prop="recharge"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="级别"
        align="center"
        prop="level"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作"
        align="center"
        width="150"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form
        :model="form"
        :rules="rules"
        ref="commission"
        label-width="100px"
      >
        <el-form-item label="渠道" prop="channel">
          <el-input v-model="form.channel" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="上游id" prop="upStreamId">
          <el-input v-model="form.upStreamId" placeholder="请输入" />
        </el-form-item>
        <!--  -->
        <el-form-item label="套餐id" prop="skuId">
          <el-input v-model="form.skuId" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="套餐名称" prop="skuName">
          <el-input v-model="form.skuName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="激活时间" style="width: 308px">
          <el-date-picker
            v-model="form.activeTime"
            type="date"
            placeholder="激活时间"
          />
        </el-form-item>
        <el-form-item label="公司收单政策" prop="companyPolicy">
          <el-input v-model.number="form.companyPolicy" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="店铺分佣政策" prop="shopPolicy">
          <el-input v-model.number="form.shopPolicy" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="公司奖罚类别" prop="companyRewardType">
          <el-input v-model="form.companyRewardType" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="店铺奖罚类别" prop="shopRewardType">
          <el-input v-model="form.shopRewardType" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="仓库" prop="warehouse">
          <el-input v-model="form.warehouse" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="台账名称" prop="meetingName">
          <el-input v-model="form.meetingName" placeholder="请输入" />
        </el-form-item>
        <!--  -->
        <el-form-item label="达成订单id" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="是否结算" prop="settlement">
          <el-select v-model="form.settlement" clearable style="width: 240px">
            <el-option key="0" label="是" value="是" />
            <el-option key="1" label="否" value="否" />
          </el-select>
        </el-form-item>
        <el-form-item label="佣金" prop="commissions">
          <el-input v-model.number="form.commissions" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="店铺分佣" prop="deptCommissions">
          <el-input
            v-model.number="form.deptCommissions"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="账单时间" style="width: 308px">
          <el-date-picker
            v-model="form.accountDate"
            type="date"
            placeholder="账单时间"
          />
        </el-form-item>
        <el-form-item label="充值" prop="recharge">
          <el-input v-model="form.recharge" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <el-select v-model="form.level" clearable style="width: 240px">
            <el-option key="0" label="T+1" value="T+1" />
            <el-option key="1" label="T+n" value="T+n" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <!--    accept=".xlsx, .xls" -->
      <el-upload
        ref="uploadRef"
        :limit="1"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <!-- <div class="el-upload__tip">
              <el-checkbox
                v-model="upload.updateSupport"
              />是否更新已经存在的数据
            </div> -->
            <!-- <span>仅允许导入xls、xlsx格式文件。</span> -->
            <!-- <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            > -->
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
